package com.atguigu.guli.service.edusms.controller;

import com.aliyuncs.exceptions.ClientException;
import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.edusms.service.MsmService;
import com.atguigu.guli.service.utils.RandomUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@RequestMapping("/edumsm/msm")
public class MsmController {

    @Autowired
    MsmService msmService;
    @Autowired
    RedisTemplate<String, String> redisTemplate;
    @GetMapping("send/{phoneNumber}")
    public R sendPhoneNumber(@PathVariable String phoneNumber) throws ClientException {
        String code1 = redisTemplate.opsForValue().get(phoneNumber);
        if (!StringUtils.isEmpty(code1)){
           return R.ok().data("message","已经发送过,请过会再发");
        }

        String code = RandomUtil.getFourBitRandom();
        Map<String,Object> param = new HashMap<>();

        param.put("code", code);
        boolean isSend = msmService.SendMessage(param,phoneNumber);
       if (isSend){
           redisTemplate.opsForValue().set(phoneNumber,code,5, TimeUnit.MINUTES);
           return R.ok();
       }
       else
           return R.error();

    }
}
